// pages/register/register.js
const util = require('../../utils/util')
const { AuthRegister } = require('../../config/api')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {

    username: '',
    password: '',
    mobile: '',
    code: '',//验证码
    wxCode: '',
    checkPsw: '',//确认密码
  },


  // 输入框事件
  inputValue(e) {
    if (e.target.dataset.input == 'username') {
      this.setData({
        username: e.detail.value
      })
    } else if (e.target.dataset.input == 'password') {
      this.setData({
        password: e.detail.value
      })
    } else if (e.target.dataset.input == 'mobile') {
      this.setData({
        mobile: e.detail.value
      })
    } else if (e.target.dataset.input == 'checkPsw') {
      this.setData({
        checkPsw: e.detail.value
      })
    } else {
      this.setData({
        code: e.detail.value
      })
    }
  },



  // 注册按钮事件
  registerBtn() {
    let that = this;
    // 判断账号密码位数
    if (this.data.username.length < 6 || this.data.password.length < 6) {
      util.showErrorToast('账号和密码的长度必须大于6位')
    } else {
      // 判断两次密码输入是否正确
      if (this.data.password == this.data.checkPsw) {
        // 判断手机号格式是否正确
        let reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
        if (reg.test(this.data.mobile)) {
          // 获取登录凭证
          wx.login({
            success: (res) => {
              if(res.code){
                that.setData({
                  wxCode: res.code
                })

                util.request(AuthRegister, {
                  username: that.data.username,
                  password: that.data.password,
                  mobile: that.data.mobile,
                  code: that.data.code,
                  wxCode: that.data.wxCode
                },'POST').then(res => {
                  console.log(res);
                  if(res.errno==0){
                    console.log(111);
                    app.globalData.hasLogin=true;
                    wx.setStorageSync('userInfo', res.data.userInfo)
                    wx.setStorage({
                      key:'token',
                      data:res.data.token,
                      success:function(){
                        wx.switchTab({
                          url: '../user/user',
                        })
                      }
                    })
                  }else{
                    util.showErrorToast(res.errmsg)
                  }
                }).catch(err => {
                  console.log("err:", err);
                  util.showErrorToast(err.errmsg)
                })
              }
            },
          })

         

          

        } else {
          util.showErrorToast('手机号格式不正确')
        }
      } else {
        util.showErrorToast('两次密码输入不一致，请检查')
        return
      }
    }


  }

})